<template>
  <div class="echarts-wall">
    <div class="dot-bg" v-if="loading"></div>
    <div class="dot-elastic dotClass" v-if="loading"></div>
    <div class="echarts-content" ref="echartsDom"></div>
  </div>
</template>

<script lang="ts" setup>
//普通地图
// @ts-ignore
import {getCurrentInstance, onMounted, ref, watch} from "vue";
// @ts-ignore
import screen_config, {getPoint} from "@/components/global/bigscreen/screen_config";

defineOptions({
  name: "EchartsMap"
});

const props = defineProps({
  url: {type: String, default: ""},
  //地图请求参数
  params: {type: Object, default: {}},
  color: {
    type: Object, default: function () {
      return ['#6bcc75', '#65c78b', '#5fc2a0', '#5abead',
        '#52b9c7', '#4fb6d2', '#4ab2e5', '#52b9c7', '#5abead', '#dfae10', '#d5b314', '#c1bb1f',
        '#f34e2b', '#f56321', '#f56f1c', '#4ab2e5', '#4fb6d2', '#f58414', '#f58f0e', '#f5a305', '#e7ab0b', '#b9be23',
        '#e7ab0b', '#dfae10', '#d5b314', '#c1bb1f', '#b9be23',
        '#a6c62c', '#96cc34', '#89d23b', '#7ed741', '#77d64c',
        '#71d162',
      ]
    }
  },
  //地图显示 区域
  map: {type: String, default: 'china'},
  // 边的颜色
  borderColor: {type: String, default: "#0068FB"},
  // 默认区域颜色
  normalAreaColorFrom: {type: String, default: "#0C3994"},
  // 默认区域颜色
  normalAreaColorEnd: {type: String, default: "#0C3994"},
  // 选中区域颜色
  emphasisColor: {type: String, default: "#0068FB"},
  // 是否显示label
  labelShow: {type: Boolean, default: false},
  // label字体
  labelFontSize: {type: Number, default: 12},
  // label字体颜色
  labelFontColor: {type: String, default: '#FFFFFF'},
  //地图 分类支持 -(map,mapFly,mapPin)
  mapType: {type: String, default: 'map'},
  //飞行(目的地)
  mapFly: {type: String, default: undefined},
  //飞行类型 : in(流入目的地),out(流出地)
  mapFlyType: {type: String, default: 'in'},
  //pin点的颜色
  pinColor: {type: String, default: '#0068FB'},
  //是否缩放
  roam: {type: Boolean, default: false},
  //特征大小
  symbolSize: {type: Number, default: 12}

});
//是否加载loading
const loading = ref<boolean>(false);

onMounted(() => {
  registerMap();
})

// @ts-ignore
let {proxy} = getCurrentInstance()
// dom 组件
const echartsDom = ref<any>(null);
//
let myEcharts: any = null;
//注册地图
const registerMap = () => {
  proxy.$http.post('/user-center/region/regionCityMap', {"region": props.map}).then((apiMap: any) => {
    if (apiMap) {
      proxy.$http.getJSON("/geoMap/" + apiMap.regionCode).then(function (data: any) {
        proxy.$echarts.registerMap(props.map, data);
        initMap().then((option: any) => {
          myEcharts = proxy.$echarts.init(echartsDom.value);
          if (myEcharts) {
            myEcharts.clear();
            myEcharts.setOption(option)
          }
        });
      });
    }
  });
}
//省/市/县坐标
const geoCoordMap: any = screen_config.geoMap;

//监听变化
watch(() => props.map, () => {
  registerMap();
})

//
const convertData = (data: any) => {
  let res = [];
  for (let i = 0; i < data.length; i++) {
    let geoCoord = geoCoordMap[data[i].name];
    if (geoCoord) {
      res.push({
        name: data[i].name,
        value: geoCoord.concat(data[i].value)
      });
    }
  }
  return res;
};
const initMap = () => {
  if (props.mapType === 'mapPin') {
    return mapPin();
  } else if (props.mapType === 'mapFly') {
    return mapFly();
  }

  return map();
}
//普通地图
const map = () => {
  return new Promise((resolve, reject) => {
    let option: any = {
      backgroundColor: 'transparent',
      series: [{
        type: 'map',
        roam: props.roam,
        label: {
          normal: {
            show: props.labelShow,
            textStyle: {
              color: props.labelFontColor,
              fontSize: props.labelFontSize,
              fontWeight: 'bold'
            },
          },
          emphasis: {
            textStyle: {
              color: '#fff',
              fontSize: props.labelFontSize,
              fontWeight: 'bold'
            },
          },
        },
        itemStyle: {
          normal: {
            borderColor: props.borderColor,
            borderWidth: 1,
            areaColor: {
              type: 'radial',
              x: 0.5,
              y: 0.5,
              r: 0.8,
              colorStops: [{
                offset: 0,
                color: props.normalAreaColorFrom, // 0% 处的颜色
              }, {
                offset: 1,
                color: props.normalAreaColorEnd, // 100% 处的颜色
              }],
              globalCoord: true, // 缺省为 false
            },
          },
          emphasis: {
            areaColor: props.emphasisColor,
            borderWidth: 1,
          },
        },
        zoom: 1.1,
        map: props.map, // 使用
      },
      ],
    };
    resolve(option);
  });
}
const geo = () => {
  return {
    map: props.map,
    show: true,
    roam: props.roam,
    label: {
      normal: {
        formatter: function (params: any) {
          return params.name;
        },
        show: false,
        color: props.labelFontColor,
        fontSize: props.labelFontSize,
        fontWeight: 'bold'
      },
      emphasis: {
        show: false,
        color: props.labelFontColor,
        fontSize: props.labelFontSize,
        fontWeight: 'bold'
      }
    },
    itemStyle: {
      normal: {
        areaColor: {
          type: 'radial',
          x: 0.5,
          y: 0.5,
          r: 0.8,
          colorStops: [{
            offset: 0,
            color: props.normalAreaColorFrom, // 0% 处的颜色
          }, {
            offset: 1,
            color: props.normalAreaColorEnd, // 100% 处的颜色
          }],
          globalCoord: true, // 缺省为 false
        },
        borderColor: props.borderColor,
        color: props.labelFontColor,
        fontSize: props.labelFontSize,
        fontWeight: 'bold'
      },
      emphasis: {
        show: false,
        areaColor: props.emphasisColor,//悬浮区背景
      }
    },
    regions: [{
      name: '南海诸岛',
      itemStyle: {
        areaColor: 'rgba(0, 10, 52, 1)',
        borderColor: 'rgba(0, 10, 52, 1)',
        normal: {
          opacity: 0,
          label: {
            show: false,
            color: "#009cc9",
          }
        }
      },
    }],
  };
}
//飞行图
const mapFly = () => {
  return new Promise(async (resolve, reject) => {
    if (props.mapFly) {
      let mapFlyPoint = await getPoint(props.mapFly);
      getData().then(async (data: any) => {
        let points: any = [{value: mapFlyPoint, name: props.mapFly}];
        let linePoints: any = [];
        for (let i = 0; i < data.length; i++) {
          let obj = data[i];
          let lonLat = await getPoint(obj.name)
          points.push({value: lonLat, name: obj.name});
          if (props.mapFlyType === 'in') {
            linePoints.push({
              coords: [lonLat, mapFlyPoint]
            });
          } else {
            linePoints.push({
              coords: [mapFlyPoint, lonLat]
            });
          }
        }
        let option: any = {
          backgroundColor: 'transparent',
          geo: geo(),
          series: [{
            type: 'effectScatter',
            coordinateSystem: 'geo',
            showEffectOn: 'render',
            zlevel: 1,
            hoverAnimation: true,
            label: {
              normal: {
                formatter: function (params: any) {
                  return params.name;
                },
                position: 'right',
                show: props.labelShow,
                color: props.labelFontColor,
                fontSize: props.labelFontSize,
                fontWeight: 'bold'
              }
            },
            itemStyle: {
              normal: {
                color: function (params: any) {
                  //点的颜色
                  return props.color[params.dataIndex]
                },
                shadowBlur: 10,
                shadowColor: '#333'
              }
            },
            symbolSize: props.symbolSize,
            data: points
          },
            {
              type: 'lines',
              zlevel: 2,
              effect: {
                show: true,
                period: 4, //箭头指向速度，值越小速度越快
                trailLength: 0.4, //特效尾迹长度[0,1]值越大，尾迹越长重
                symbol: 'arrow', //箭头图标
                symbolSize: props.symbolSize / 3, //图标大小
              },
              lineStyle: {
                normal: {
                  color: function (params: any) {
                    return props.color[params.dataIndex]
                  },
                  width: 1, //线条宽度
                  opacity: 0.1, //尾迹线条透明度
                  curveness: .3 //尾迹线条曲直度
                }
              },
              data: linePoints
            }
          ]
        };
        resolve(option)
      });
    }
  });
}
//pin图
const mapPin = () => {
  return new Promise((resolve, reject) => {
    getData().then((data: any) => {
      let option: any = {
        backgroundColor: "transparent",
        visualMap: {
          show: false,
          min: 0,
          max: 500000,
          left: 'left',
          top: 'bottom',
          text: ['高', '低'], // 文本，默认为数值文本
          calculable: true,
          seriesIndex: [1],
          inRange: {}
        },
        geo: geo(),
        series: [
          {
            symbolSize: props.symbolSize / 4,
            label: {
              normal: {
                formatter: '{b}',
                position: 'right',
                show: props.labelShow,
                color: props.labelFontColor,
                fontSize: props.labelFontSize,
                fontWeight: 'bold'
              },
              emphasis: {
                show: false
              }
            },
            itemStyle: {
              normal: {
                color: props.labelFontColor,
                fontSize: props.labelFontSize,
                fontWeight: 'bold'
              }
            },
            name: 'light',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: convertData(data),

          },
          {
            type: 'scatter',
            coordinateSystem: 'geo',
            symbol: 'pin',
            symbolSize: [50, 50],
            label: {
              normal: {
                show: true,
                textStyle: {
                  color: '#fff',
                  fontSize: 9,
                },
                formatter(value: any) {
                  return value.data.value[2]
                }
              }
            },
            itemStyle: {
              normal: {
                color: props.pinColor, //标志颜色
              }
            },
            data: convertData(data),
            showEffectOn: 'render',
            rippleEffect: {
              brushType: 'stroke'
            },
            hoverAnimation: true
          },
        ]
      };
      resolve(option);
    });
  });

}

const getData = () => {
  return new Promise((resolve, reject) => {
    proxy.$http.post(props.url, props.params)
        .then((apiResponse: any) => {
          if (apiResponse.success || apiResponse.data) {
            let echartsData = apiResponse.data.echartsData;
            let i = 0;
            let searData: any = [];
            Object.keys(echartsData).forEach((key: string) => {
              if (i === 0) {
                searData = echartsData[key];
              }
            })
            resolve(searData);
          }
        }).catch((err: any) => {
      reject(err)
    });
  });
}
</script>

<style scoped>

</style>